package com.qianduo.util;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Collection;
import java.util.List;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
/**
 * @author Charis
 */
@SuppressWarnings({"rawtypes"})
public class HibernateUtil extends HibernateDaoSupport {
	protected String className	= this.getClass().getName();
	
	public HibernateUtil() {
	}
	
	public ResultSet queryBySql(Statement st,String sql) throws Exception{
		return st.executeQuery(sql);
	}
	
	public PreparedStatement getPreparedStatement(Connection conn,String sql) throws Exception{
		return conn.prepareStatement(sql);
	}
	
	public Connection getConnection() throws Exception{
		return SessionFactoryUtils.getDataSource(getSessionFactory()).getConnection();
	}
	
	public void closeConnection(ResultSet rs,Statement state,Connection conn){
		try{
			rs.close();
		}catch(Exception e){
		}
		try{
			state.close();
		}catch(Exception e){
		}
		try{
			conn.close();
		}catch(Exception e){			
		}
		
	}
	
	public void save(Object obj) {
		super.getHibernateTemplate().save(obj);
	}

	public void saveOrUpdate(Object obj) {
		super.getHibernateTemplate().saveOrUpdate(obj);
	}
	
	public void saveOrUpdateAll(Collection<Object> coll) {
		super.getHibernateTemplate().saveOrUpdateAll(coll);
	}
	
	public List query(String sql) {
		return super.getHibernateTemplate().find(sql);
	}

	public List querySql(String sql){
		 return getSession().createSQLQuery(sql).list();
	}
	
	public List query(String sql, Object[] params) {
		return super.getHibernateTemplate().find(sql, params);
	}

	public List query(String sql, Object param) {
		return super.getHibernateTemplate().find(sql, param);
	}

	public List loadAll(Class clazz) {
		return super.getHibernateTemplate().loadAll(clazz);
	}

	public void removeObject(Object obj) {
		super.getHibernateTemplate().delete(obj);
	}

	public void removeObject(Class clazz, Serializable id) {
		getHibernateTemplate().delete(getObject(clazz, id));
	}

	public Object getObject(Class clazz, Serializable id) {
		Object o = getHibernateTemplate().get(clazz, id);
		if (o == null) {
			throw new ObjectRetrievalFailureException(clazz, id);
		}
		return o;
	}

	public Object loadObject(Class clazz, Serializable id) {
		Object o = getHibernateTemplate().load(clazz, id);
		if (o == null) {
			throw new ObjectRetrievalFailureException(clazz, id);
		}
		return o;
	}

	public void update(Object obj) {
		super.getHibernateTemplate().update(obj);

	}

	public void flush() {
		super.getHibernateTemplate().flush();
	}
}
